﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using System.Web.Script.Serialization;

namespace jnlamp.Web.api
{
    /// <summary>
    /// hanlder 的摘要说明
    /// </summary>
    public class hanlder : IHttpHandler
    {

        jnlamp.BLL.scdstatus scdm = new BLL.scdstatus();
        jnlamp.BLL.scd_set_opt optm = new BLL.scd_set_opt();
        jnlamp.BLL.scd_set_time timem = new BLL.scd_set_time();
        jnlamp.BLL.scd_set_time sm = new BLL.scd_set_time();

        public void ProcessRequest(HttpContext context)
        {
            string ac = "";
            if (null != context.Request.Form["action"])
            {//获取前台传来的值  
                ac = context.Request.Form["action"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["action"])
            {
                ac = context.Request.QueryString["action"].ToString().Trim();
            }
            #region 获取前台传来的值
            string gprs_id = "";
            if (null != context.Request.Form["gprs_id"])
            {//获取前台传来的值  
                gprs_id = context.Request.Form["gprs_id"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["gprs_id"])
            {
                gprs_id = context.Request.QueryString["gprs_id"].ToString();
            }

            string scd_set_opt_id = "";
            if (null != context.Request.Form["scd_set_opt_id"])
            {//获取前台传来的值  
                scd_set_opt_id = context.Request.Form["scd_set_opt_id"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["scd_set_opt_id"])
            {
                scd_set_opt_id = context.Request.QueryString["scd_set_opt_id"].ToString();
            }
            string opt = "";
            if (null != context.Request.Form["opt"])
            {//获取前台传来的值  
                opt = context.Request.Form["opt"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["opt"])
            {
                opt = context.Request.QueryString["opt"].ToString();
            }
            string scd_id = "";
            if (null != context.Request.Form["scd_id"])
            {//获取前台传来的值  
                scd_id = context.Request.Form["scd_id"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["scd_id"])
            {
                scd_id = context.Request.QueryString["scd_id"].ToString();
            }
            string kdsj = "";
            if (null != context.Request.Form["kdsj"])
            {//获取前台传来的值  
                kdsj = context.Request.Form["kdsj"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["kdsj"])
            {
                kdsj = context.Request.QueryString["kdsj"].ToString();
            }
            string kdsc = "";
            if (null != context.Request.Form["kdsc"])
            {//获取前台传来的值  
                kdsc = context.Request.Form["kdsc"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["kdsc"])
            {
                kdsc = context.Request.QueryString["kdsc"].ToString();
            }
            string ts = "";
            if (null != context.Request.Form["ts"])
            {//获取前台传来的值  
                ts = context.Request.Form["ts"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["ts"])
            {
                ts = context.Request.QueryString["ts"].ToString();
            }
            string scd_set_time_id = "";
            if (null != context.Request.Form["scd_set_time_id"])
            {//获取前台传来的值  
                scd_set_time_id = context.Request.Form["scd_set_time_id"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["scd_set_time_id"])
            {
                scd_set_time_id = context.Request.QueryString["scd_set_time_id"].ToString();
            }
            #endregion

            if (ac == "QueryStatus")
            {
                Get_status(gprs_id, context);
            }

            if (ac == "QueryOpt")
            {
                GetList_scd_opt(context);
            }

            if (ac == "delScd")
            {
                DelScd(scd_set_opt_id, context);
            }
            if (ac == "AddGPRS")
            {
                AddGPRS(gprs_id, opt, context);
            }
            if (ac == "QueryDDl")
            {
                QueryDDl(gprs_id, context);
            }
            if (ac == "AddScd")
            {
                AddScd(gprs_id,scd_id, opt, context);
            }
            if (ac == "AddScdTime")
            {
                AddScdTime(gprs_id, kdsj,kdsc,ts, context);
            }
            if (ac == "delScdTime")
            {
                delScdTime(scd_set_time_id,context);
            }
            if (ac == "QueryTime")
            {
                GetList_scd_set_time(context);
            }
            if (ac== "QueryAutoComplete")
            {
                QueryDDl(gprs_id, context);
            }
              
        }

        private void AddScdTime(string gprs_id, string kdsj,string kdsc,string ts, HttpContext context)
        {
            jnlamp.Model.scd_set_time s = new Model.scd_set_time();
           
            s.gprs_id = gprs_id;
            s.kdsc = kdsc;
            s.kdsj = kdsj;
            s.readcount = 3;
            s.setcount = 3;
            s.settime = DateTime.Now;
            s.ts = int.Parse(ts);

            int vf = 0;

            for (int i = 0; i < kdsc.Length; i++)
            {
                vf += int.Parse(kdsc[i].ToString());
            }
            for (int i = 0; i < kdsj.Length; i++)
            {
                vf += int.Parse(kdsj[i].ToString());
            }
            for (int i = 0; i < ts.Length; i++)
            {
                vf += int.Parse(ts[i].ToString());
            }

            s.vf = vf;

            if (sm.Add(s)>0)
            {
                List<jnlamp.Model.scdstatus> ls = scdm.GetModelList(" gprs_id='"+gprs_id+"' ");

                if (ls.Count > 0)
                {
                    jnlamp.Model.scdstatus scdstatus = ls[0];

                    scdstatus.kdsc = kdsc;
                    scdstatus.kdsj = kdsj;
                    scdstatus.ts = int.Parse(ts);
                    scdstatus.vf = vf;
                    
                    DataSet ds_opt = optm.GetList(" gprs_id='" + gprs_id + "' order by readtime desc ");

                    if (ds_opt.Tables[0].Rows.Count > 0)
                    {
                        scdstatus.opt = ds_opt.Tables[0].Rows[0]["opt"].ToString();
                    }

                    scdm.Update(scdstatus);
                }
                else
                {
                    jnlamp.Model.scdstatus scdstatus = new Model.scdstatus ();

                    scdstatus.gprs_id = gprs_id;
                    scdstatus.kdsc = kdsc;
                    scdstatus.kdsj = kdsj;
                    scdstatus.ts = int.Parse(ts);
                    scdstatus.vf = vf;

                    DataSet ds_opt = optm.GetList(" gprs_id='" + gprs_id + "' order by readtime desc ");

                    if (ds_opt.Tables[0].Rows.Count > 0)
                    {
                        scdstatus.opt = ds_opt.Tables[0].Rows[0]["opt"].ToString();
                    }

                    scdm.Add(scdstatus);
                }

                context.Response.Write("T");
                context.Response.End();
            }
            else
            {
                context.Response.Write("F");
                context.Response.End();
            }
            
        }

        // 获取网关下所有灯(scdInfo)
        private void QueryAutoComplete(string gprs_id, HttpContext context,string keyword)
        {
            jnlamp.BLL.scdInfo sm = new BLL.scdInfo();

            DataSet ds = sm.GetListLampId(" gprs_id= '" + gprs_id + "' and scd_id like '%"+ keyword + "%' ");

            List<string> proList = new List<string>();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                //此处选项一般从数据库中读取，然后循环添加给countrylist对象即可。
                proList.Add(ds.Tables[0].Rows[i]["scd_id"].ToString());
            }

            //string strJson = ToJson.DataTable2Json1(ds.Tables[0]);//DataSet数据转化为Json数据  
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strJson = serializer.Serialize(proList.ToArray());
            context.Response.Write(strJson);//返回给前台页面  
            context.Response.End();

        }


        private void AddScd(string gprs_id, string scd_id, string opt, HttpContext context)
        {
            jnlamp.Model.scd_set_opt s = new Model.scd_set_opt();
            jnlamp.BLL.scd_set_opt sm = new BLL.scd_set_opt();

            s.gprs_id = gprs_id;
            s.lamp_id = scd_id;
            s.opt = opt;
            s.setcount = 3;
            s.settime = DateTime.Now;
            s.readcount = 3;

            if (sm.Add(s) > 0)
            {
                context.Response.Write("T");
                context.Response.End();
            }
            else
            {
                context.Response.Write("F");
                context.Response.End();
            }
        }
        
        // 获取网关下所有灯(scdInfo)
        private void QueryDDl(string gprs_id, HttpContext context)
        {
            jnlamp.BLL.scdInfo sm = new BLL.scdInfo();

            DataSet ds = sm.GetListLampId(" gprs_id= '"+gprs_id+"' and scd_id is not null ");

            string strJson = ToJson.DataTable2Json1(ds.Tables[0]);//DataSet数据转化为Json数据  
            context.Response.Write(strJson);//返回给前台页面  
            context.Response.End();
        
        }
        private void AddGPRS(string gprs_id, string opt, HttpContext context)
        {
            jnlamp.Model.scd_set_opt s = new Model.scd_set_opt();
            jnlamp.BLL.scd_set_opt sm = new BLL.scd_set_opt();

            s.gprs_id = gprs_id;
            s.opt = opt;
            s.setcount = 3;
            s.settime = DateTime.Now;
            s.readcount = 3;

            if (sm.Add(s) > 0)
            {
                context.Response.Write("T");
                context.Response.End();
            }
            else
            {
                context.Response.Write("F");
                context.Response.End();
            }
        
        
        }
        private void delScdTime(string scd_set_time_id, HttpContext context)
        {
            if (!string.IsNullOrEmpty(scd_set_time_id))
            {
                bool re = timem.Delete(Convert.ToInt32(scd_set_time_id));

                if (re)
                {
                    context.Response.Write("T");
                    context.Response.End();
                }
                else
                {
                    context.Response.Write("F");
                    context.Response.End();
                }

            }
        }
        private void DelScd(string scd_set_opt_id,HttpContext context)
        {
            if (!string.IsNullOrEmpty(scd_set_opt_id))
            {
                bool re = optm.Delete(Convert.ToInt32(scd_set_opt_id));

                if (re)
                {
                    context.Response.Write("T");
                    context.Response.End();
                }
                else
                {
                    context.Response.Write("F");
                    context.Response.End();
                }
                
            }
        }
        private void GetList_scd_opt(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string gprs_id = "";
            if (null != context.Request.Form["gprs_id"])
            {//获取前台传来的值  
                gprs_id = context.Request.Form["gprs_id"].ToString().Trim();
            }

            //================================================================  
            //获取分页和排序信息：页大小，页码，排序方式，排序字段  
            int pageRows, page;
            pageRows = 10;
            page = 1;
            string order, sort, oderby; order = sort = oderby = "";
            if (null != context.Request.Form["rows"])
            {
                string t = context.Request.Form["rows"];
                pageRows = int.Parse(context.Request.Form["rows"].ToString().Trim());
            }
            if (null != context.Request.Form["page"])
            {
                page = int.Parse(context.Request.Form["page"].ToString().Trim());
            }
            if (null != context.Request.Form["sort"])
            {
                order = context.Request.Form["sort"].ToString().Trim();
            }
            if (null != context.Request.Form["order"])
            {
                sort = context.Request.Form["order"].ToString().Trim();
            }
            //===================================================================  
            //组合查询语句：条件+排序  
            StringBuilder strWhere = new StringBuilder();
            //if (st != "")
            //{
            //    strWhere.AppendFormat(" dtitle like '%{0}%' and ", uname);
            //}
            //if (StartTime != "")
            //{
            //    strWhere.AppendFormat(" infotime>='{0}' and ", StartTime);
            //}
            //if (EndTime != "")
            //{
            //    strWhere.AppendFormat(" infotime<='{0}' and ", EndTime);
            //}

            if (!string.IsNullOrEmpty(gprs_id))
            {
                strWhere.AppendFormat(" gprs_id='{0}' and ", gprs_id);
            }
            else
            {
                strWhere.AppendFormat(" gprs_id='' and ");
            }
            

            //删除多余的and  
            int startindex = strWhere.ToString().LastIndexOf("and");//获取最后一个and的位置  
            if (startindex >= 0)
            {
                strWhere.Remove(startindex, 3);//删除多余的and关键字  
            }
            if (sort != "" && order != "")
            {
                //strWhere.AppendFormat(" order by {0} {1}", sort, order);//添加排序  
                oderby = order + " " + sort;
            }

            //调用分页的GetList方法  
            DataSet ds = optm.GetListByPage(strWhere.ToString(), oderby, (page - 1) * pageRows + 1, page * pageRows);
            int count = optm.GetRecordCount(strWhere.ToString());//获取条数  
            string strJson = ToJson.Dataset2Json(ds, count, 50);//DataSet数据转化为Json数据                
            context.Response.Write(strJson);//返回给前台页面  
            context.Response.End();
        }
        private void GetList_scd_set_time(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string gprs_id = "";
            if (null != context.Request.Form["gprs_id"])
            {//获取前台传来的值  
                gprs_id = context.Request.Form["gprs_id"].ToString().Trim();
            }

            //================================================================  
            //获取分页和排序信息：页大小，页码，排序方式，排序字段  
            int pageRows, page;
            pageRows = 10;
            page = 1;
            string order, sort, oderby; order = sort = oderby = "";
            if (null != context.Request.Form["rows"])
            {
                string t = context.Request.Form["rows"];
                pageRows = int.Parse(context.Request.Form["rows"].ToString().Trim());
            }
            if (null != context.Request.Form["page"])
            {
                page = int.Parse(context.Request.Form["page"].ToString().Trim());
            }
            if (null != context.Request.Form["sort"])
            {
                order = context.Request.Form["sort"].ToString().Trim();
            }
            if (null != context.Request.Form["order"])
            {
                sort = context.Request.Form["order"].ToString().Trim();
            }
            //===================================================================  
            //组合查询语句：条件+排序  
            StringBuilder strWhere = new StringBuilder();
            //if (st != "")
            //{
            //    strWhere.AppendFormat(" dtitle like '%{0}%' and ", uname);
            //}
            //if (StartTime != "")
            //{
            //    strWhere.AppendFormat(" infotime>='{0}' and ", StartTime);
            //}
            //if (EndTime != "")
            //{
            //    strWhere.AppendFormat(" infotime<='{0}' and ", EndTime);
            //}

            if (!string.IsNullOrEmpty(gprs_id))
            {
                strWhere.AppendFormat(" gprs_id='{0}' and ", gprs_id);
            }
            else
            {
                strWhere.AppendFormat(" gprs_id='' and ");
            }

            //删除多余的and  
            int startindex = strWhere.ToString().LastIndexOf("and");//获取最后一个and的位置  
            if (startindex >= 0)
            {
                strWhere.Remove(startindex, 3);//删除多余的and关键字  
            }
            if (sort != "" && order != "")
            {
                //strWhere.AppendFormat(" order by {0} {1}", sort, order);//添加排序  
                oderby = order + " " + sort;
            }

            //调用分页的GetList方法  
            DataSet ds = timem.GetListByPage(strWhere.ToString(), oderby, (page - 1) * pageRows + 1, page * pageRows);
            int count = timem.GetRecordCount(strWhere.ToString());//获取条数  
            string strJson = ToJson.Dataset2Json(ds, count, 50);//DataSet数据转化为Json数据                
            context.Response.Write(strJson);//返回给前台页面  
            context.Response.End();
        }
        private void Get_status(string gprs_id, HttpContext context)
        {
            DataSet ds = scdm.GetList(" gprs_id = '" + gprs_id + "' ");

            string strJson = ToJson.DataTable2Json1(ds.Tables[0]);//DataSet数据转化为Json数据  
            context.Response.Write(strJson);//返回给前台页面  
            context.Response.End();
        

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}